using Microsoft.AspNetCore.Mvc;
using MVCWeekOne.Models;
using System.Text;
using System.Text.Json;

namespace MVCWeekOne.Controllers
{
    public class DefectiveSummaryController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;
        private readonly string _readApiUrl;

        public DefectiveSummaryController(IConfiguration configuration, HttpClient httpClient)
        {
            _configuration = configuration;
            _httpClient = httpClient;
            _readApiUrl = _configuration["ApiSettings:ReadApiUrl"] ?? "http://localhost:5089/api";
        }

        /// <summary>
        /// 不良品汇总页面
        /// </summary>
        public IActionResult Index()
        {
            ViewBag.ReadApiUrl = _readApiUrl;
            return View();
        }

        /// <summary>
        /// 获取不良品汇总分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDefectiveSummary(
            string? workOrderCode,
            string? productCode,
            string? productName,
            string? processCode,
            string? processName,
            string? producer,
            string? productionStartTimeBegin,
            string? productionStartTimeEnd,
            string? productionEndTimeBegin,
            string? productionEndTimeEnd,
            string? defectiveItem,
            int? processPlanQuantityMin,
            int? processPlanQuantityMax,
            int? reportQuantityMin,
            int? reportQuantityMax,
            int? qualifiedQuantityMin,
            int? qualifiedQuantityMax,
            string? sortField,
            string? sortOrder,
            int pageIndex = 1,
            int pageSize = 10)
        {
            try
            {
                var queryParams = new List<string>();
                
                if (!string.IsNullOrEmpty(workOrderCode))
                    queryParams.Add($"workOrderCode={Uri.EscapeDataString(workOrderCode)}");
                if (!string.IsNullOrEmpty(productCode))
                    queryParams.Add($"productCode={Uri.EscapeDataString(productCode)}");
                if (!string.IsNullOrEmpty(productName))
                    queryParams.Add($"productName={Uri.EscapeDataString(productName)}");
                if (!string.IsNullOrEmpty(processCode))
                    queryParams.Add($"processCode={Uri.EscapeDataString(processCode)}");
                if (!string.IsNullOrEmpty(processName))
                    queryParams.Add($"processName={Uri.EscapeDataString(processName)}");
                if (!string.IsNullOrEmpty(producer))
                    queryParams.Add($"producer={Uri.EscapeDataString(producer)}");
                if (!string.IsNullOrEmpty(productionStartTimeBegin))
                    queryParams.Add($"productionStartTimeBegin={Uri.EscapeDataString(productionStartTimeBegin)}");
                if (!string.IsNullOrEmpty(productionStartTimeEnd))
                    queryParams.Add($"productionStartTimeEnd={Uri.EscapeDataString(productionStartTimeEnd)}");
                if (!string.IsNullOrEmpty(productionEndTimeBegin))
                    queryParams.Add($"productionEndTimeBegin={Uri.EscapeDataString(productionEndTimeBegin)}");
                if (!string.IsNullOrEmpty(productionEndTimeEnd))
                    queryParams.Add($"productionEndTimeEnd={Uri.EscapeDataString(productionEndTimeEnd)}");
                if (!string.IsNullOrEmpty(defectiveItem))
                    queryParams.Add($"defectiveItem={Uri.EscapeDataString(defectiveItem)}");
                if (processPlanQuantityMin.HasValue)
                    queryParams.Add($"processPlanQuantityMin={processPlanQuantityMin}");
                if (processPlanQuantityMax.HasValue)
                    queryParams.Add($"processPlanQuantityMax={processPlanQuantityMax}");
                if (reportQuantityMin.HasValue)
                    queryParams.Add($"reportQuantityMin={reportQuantityMin}");
                if (reportQuantityMax.HasValue)
                    queryParams.Add($"reportQuantityMax={reportQuantityMax}");
                if (qualifiedQuantityMin.HasValue)
                    queryParams.Add($"qualifiedQuantityMin={qualifiedQuantityMin}");
                if (qualifiedQuantityMax.HasValue)
                    queryParams.Add($"qualifiedQuantityMax={qualifiedQuantityMax}");
                if (!string.IsNullOrEmpty(sortField))
                    queryParams.Add($"sortField={Uri.EscapeDataString(sortField)}");
                if (!string.IsNullOrEmpty(sortOrder))
                    queryParams.Add($"sortOrder={Uri.EscapeDataString(sortOrder)}");
                
                queryParams.Add($"index={pageIndex}");
                queryParams.Add($"size={pageSize}");

                var url = $"{_readApiUrl}/DefectiveSummary/GetDefectiveSummary?{string.Join("&", queryParams)}";
                
                var response = await _httpClient.GetAsync(url);
                var content = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    return Json(JsonSerializer.Deserialize<object>(content));
                }
                else
                {
                    return Json(new { success = false, message = "获取数据失败", error = content });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "系统错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 导出不良品汇总数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportDefectiveSummary(
            string? workOrderCode,
            string? productCode,
            string? productName,
            string? processCode,
            string? processName,
            string? producer,
            string? productionStartTimeBegin,
            string? productionStartTimeEnd,
            string? productionEndTimeBegin,
            string? productionEndTimeEnd,
            string? defectiveItem,
            int? processPlanQuantityMin,
            int? processPlanQuantityMax,
            int? reportQuantityMin,
            int? reportQuantityMax,
            int? qualifiedQuantityMin,
            int? qualifiedQuantityMax)
        {
            try
            {
                var queryParams = new List<string>();
                
                if (!string.IsNullOrEmpty(workOrderCode))
                    queryParams.Add($"workOrderCode={Uri.EscapeDataString(workOrderCode)}");
                if (!string.IsNullOrEmpty(productCode))
                    queryParams.Add($"productCode={Uri.EscapeDataString(productCode)}");
                if (!string.IsNullOrEmpty(productName))
                    queryParams.Add($"productName={Uri.EscapeDataString(productName)}");
                if (!string.IsNullOrEmpty(processCode))
                    queryParams.Add($"processCode={Uri.EscapeDataString(processCode)}");
                if (!string.IsNullOrEmpty(processName))
                    queryParams.Add($"processName={Uri.EscapeDataString(processName)}");
                if (!string.IsNullOrEmpty(producer))
                    queryParams.Add($"producer={Uri.EscapeDataString(producer)}");
                if (!string.IsNullOrEmpty(productionStartTimeBegin))
                    queryParams.Add($"productionStartTimeBegin={Uri.EscapeDataString(productionStartTimeBegin)}");
                if (!string.IsNullOrEmpty(productionStartTimeEnd))
                    queryParams.Add($"productionStartTimeEnd={Uri.EscapeDataString(productionStartTimeEnd)}");
                if (!string.IsNullOrEmpty(productionEndTimeBegin))
                    queryParams.Add($"productionEndTimeBegin={Uri.EscapeDataString(productionEndTimeBegin)}");
                if (!string.IsNullOrEmpty(productionEndTimeEnd))
                    queryParams.Add($"productionEndTimeEnd={Uri.EscapeDataString(productionEndTimeEnd)}");
                if (!string.IsNullOrEmpty(defectiveItem))
                    queryParams.Add($"defectiveItem={Uri.EscapeDataString(defectiveItem)}");
                if (processPlanQuantityMin.HasValue)
                    queryParams.Add($"processPlanQuantityMin={processPlanQuantityMin}");
                if (processPlanQuantityMax.HasValue)
                    queryParams.Add($"processPlanQuantityMax={processPlanQuantityMax}");
                if (reportQuantityMin.HasValue)
                    queryParams.Add($"reportQuantityMin={reportQuantityMin}");
                if (reportQuantityMax.HasValue)
                    queryParams.Add($"reportQuantityMax={reportQuantityMax}");
                if (qualifiedQuantityMin.HasValue)
                    queryParams.Add($"qualifiedQuantityMin={qualifiedQuantityMin}");
                if (qualifiedQuantityMax.HasValue)
                    queryParams.Add($"qualifiedQuantityMax={qualifiedQuantityMax}");

                var url = $"{_readApiUrl}/DefectiveSummary/ExportDefectiveSummary";
                if (queryParams.Any())
                {
                    url += "?" + string.Join("&", queryParams);
                }

                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var fileBytes = await response.Content.ReadAsByteArrayAsync();
                    var fileName = $"不良品汇总_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return Json(new { success = false, message = "导出失败", error = errorContent });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "导出失败", error = ex.Message });
            }
        }
    }
} 